import 'dart:math';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:card_swiper/card_swiper.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_staggered_grid_view/flutter_staggered_grid_view.dart';
import 'package:get/get.dart';
import 'package:yi_shop/extensions/fun.dart';
import 'package:yi_shop/model/product.dart';
import 'package:yi_shop/route/index.dart';
import 'package:yi_shop/utils/clipboard.dart';
import 'package:yi_shop/utils/colors.dart';
import 'package:yi_shop/utils/styles.dart';
import 'package:yi_shop/utils/svg.dart';
import 'package:yi_shop/utils/tools.dart';

class GroupInfoController extends GetxController {
  List<String> imgUrlList = [
    'https://cbu01.alicdn.com/img/ibank/O1CN01fpjsxe1WZp40Z4DBN_!!2216437262803-0-cib.jpg',
    'https://cbu01.alicdn.com/img/ibank/O1CN01RNK7zR1WZp40aCImM_!!2216437262803-0-cib.jpg',
    'https://cbu01.alicdn.com/img/ibank/O1CN01tPY6Eo1WZp40Z5gdA_!!2216437262803-0-cib.jpg',
    'https://cbu01.alicdn.com/img/ibank/O1CN01Get8ju1WZp41gNQBk_!!2216437262803-0-cib.jpg',
  ];

  RxList<_TeamworkModel> teamList = RxList([]);

  List<List<SpellOrderProductModel>> dataList = [];

  @override
  void onInit() {
    initData();
    initTeam();
    super.onInit();
  }

  void initData() {
    var r = Random.secure();
    for (var i = 0; i < 10; i++) {
      List<SpellOrderProductModel> tmp = [];
      for (var j = 0; j < 2; j++) {
        tmp.add(SpellOrderProductModel(
            avatar:
                'https://img0.baidu.com/it/u=4130322821,3017185594&fm=253&fmt=auto&app=138&f=JPEG?w=500&h=500',
            nickname: '李四',
            price: 100.0 + r.nextInt(500),
            spellCount: r.nextInt(50),
            differCount: r.nextInt(20),
            residueTime: '${r.nextInt(23)}:${r.nextInt(59)}:${r.nextInt(59)}'));
      }
      dataList.add(tmp);
    }
  }

  void initTeam() {
    teamList.add(_TeamworkModel(number: 2, price: 250));
    teamList.add(_TeamworkModel(number: 5, price: 240));
    teamList.add(_TeamworkModel(number: 10, price: 215));
    teamList.add(_TeamworkModel(number: 20, price: 190));
  }
}

class GroupInfoPage extends GetView<GroupInfoController> {
  const GroupInfoPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        leading: ToolsUtils.builderLeading(),
        title: const Text('商品详情'),
        actions: [
          IconButton(
              // 分享
              onPressed: () {}.useDebounce(openShare, delay: const Duration(milliseconds: 10)),
              icon: const Icon(
                Icons.share_outlined,
                color: Colors.white,
                size: 20,
                weight: 500,
              ))
        ],
      ),
      body: SingleChildScrollView(
        child: Column(
          children: [
            SizedBox(
              height: 211,
              child: Swiper.list<String>(
                  list: controller.imgUrlList,
                  containerWidth: Get.width,
                  containerHeight: 211,
                  itemHeight: 211,
                  itemWidth: Get.width,
                  autoplay: true,
                  autoplayDelay: 5000,
                  duration: 500,
                  pagination: SwiperPagination(
                      builder: DotSwiperPaginationBuilder(
                          activeColor: Colors.white,
                          color: ColorsUtils.parseColorFromHexString(ColorsUtils.color6666),
                          size: 10.w,
                          activeSize: 10.w),
                      alignment: Alignment.bottomCenter),
                  builder: (_, url, index) {
                    return CachedNetworkImage(
                      imageUrl: url,
                      height: 211,
                      width: Get.width,
                      fit: BoxFit.fill,
                    );
                  }),
            ),
            Container(
              padding: EdgeInsets.symmetric(vertical: 15.w, horizontal: 15.h),
              decoration: const BoxDecoration(color: Colors.white),
              child: Column(
                children: [
                  Align(
                    alignment: Alignment.centerLeft,
                    child: Wrap(
                      spacing: 10.w,
                      crossAxisAlignment: WrapCrossAlignment.center,
                      alignment: WrapAlignment.start,
                      children: [
                        Text(
                          '恒威燃油宝',
                          style: StylesUtils.customTextStyle(color: ColorsUtils.color3333),
                        ),
                        Text(
                          '¥275.00',
                          style: StylesUtils.textStyle(
                              color: ColorsUtils.rgba(0, 0, 0, 0.447058823529412),
                              decorationStyle: TextDecorationStyle.solid,
                              decorationThickness: 1.0,
                              decoration: TextDecoration.lineThrough,
                              decorationColor: ColorsUtils.rgba(0, 0, 0, 0.447058823529412)),
                        )
                      ],
                    ),
                  ),
                  Container(
                    alignment: Alignment.centerLeft,
                    margin: EdgeInsets.only(top: 10.h),
                    child: Text(
                      '恒威第五代强力燃油宝积碳清洁剂50ml x 5 瓶',
                      style: StylesUtils.customTextStyle(
                          color: ColorsUtils.color9999, fontSize: StylesUtils.fontSize13),
                    ),
                  )
                ],
              ),
            ),
            Container(
              height: 35.h,
              padding: EdgeInsets.symmetric(horizontal: 15.w),
              child: Row(
                mainAxisAlignment: MainAxisAlignment.spaceBetween,
                children: [
                  Text(
                    '${controller.dataList.length * 2}人在拼单',
                    style: StylesUtils.customTextStyle(color: ColorsUtils.color3333),
                  ),
                  RichText(
                      text: TextSpan(children: [
                    TextSpan(
                        text: '查看更多 ',
                        style: StylesUtils.customTextStyle(
                          color: ColorsUtils.colorAaaa,
                        )),
                    WidgetSpan(
                        child: Icon(
                          Icons.arrow_forward_ios,
                          color: ColorsUtils.parseColorFromHexString(ColorsUtils.colorAaaa),
                          size: 14.sp,
                          weight: 400,
                        ),
                        alignment: PlaceholderAlignment.middle)
                  ]))
                ],
              ),
            ),
            Container(
              alignment: Alignment.center,
              padding: EdgeInsets.symmetric(vertical: 15.h),
              decoration: const BoxDecoration(color: Colors.white),
              child: SizedBox(
                width: 346.w,
                height: 90.h,
                child: Swiper.list(
                  list: controller.dataList,
                  autoplay: true,
                  autoplayDelay: 5000,
                  duration: 500,
                  scrollDirection: Axis.vertical,
                  builder: (_, list, i) {
                    return Column(
                      children: list
                          .asMap()
                          .map((index, row) {
                            return MapEntry(
                                index,
                                Container(
                                  margin:
                                      EdgeInsets.only(bottom: index < list.length - 1 ? 20.h : 0),
                                  child: Row(
                                    mainAxisAlignment: MainAxisAlignment.spaceBetween,
                                    crossAxisAlignment: CrossAxisAlignment.start,
                                    children: [
                                      Container(
                                        alignment: Alignment.center,
                                        margin: EdgeInsets.only(right: 5.w),
                                        child: CircleAvatar(
                                          radius: 20,
                                          backgroundImage: NetworkImage(row.avatar),
                                        ),
                                      ),
                                      Column(
                                        children: [
                                          Container(
                                            alignment: Alignment.centerLeft,
                                            child: Text(
                                              row.nickname,
                                              style: StylesUtils.customTextStyle(
                                                  color: ColorsUtils.color3333),
                                            ),
                                          ),
                                          Container(
                                            margin: EdgeInsets.only(top: 10.w),
                                            alignment: Alignment.centerLeft,
                                            child: Text(
                                              '￥${row.price}',
                                              style: StylesUtils.customTextStyle(
                                                  color: ColorsUtils.colorE419,
                                                  fontSize: StylesUtils.fontSize13),
                                            ),
                                          )
                                        ],
                                      ),
                                      Expanded(
                                          child: Container(
                                        padding: EdgeInsets.only(right: 10.w),
                                        child: Column(
                                          children: [
                                            Container(
                                              alignment: Alignment.centerRight,
                                              child: Text.rich(TextSpan(
                                                  style: StylesUtils.customTextStyle(
                                                      color: ColorsUtils.color2a2a,
                                                      fontSize: StylesUtils.fontSize13),
                                                  children: [
                                                    TextSpan(text: '${row.spellCount}人，还差'),
                                                    TextSpan(
                                                        text: '${row.differCount}人',
                                                        style: StylesUtils.customTextStyle(
                                                            fontSize: StylesUtils.fontSize13,
                                                            color: ColorsUtils.colorE419)),
                                                    const TextSpan(text: '拼成')
                                                  ])),
                                            ),
                                            Container(
                                              alignment: Alignment.centerRight,
                                              margin: EdgeInsets.only(top: 10.w),
                                              child: Text(
                                                '剩余 ${row.residueTime}',
                                                style: StylesUtils.textStyle(
                                                    color: ColorsUtils.rgba(
                                                        0, 0, 0, 0.447058823529412),
                                                    fontSize: StylesUtils.fontSize13),
                                              ),
                                            )
                                          ],
                                        ),
                                      )),
                                      Center(
                                        child: Container(
                                          constraints:
                                              const BoxConstraints.tightFor(width: 94, height: 35),
                                          child: TextButton(
                                              onPressed: () {
                                                Get.toNamed(RoutePath.groupConfirm);
                                              },
                                              style: ButtonStyle(
                                                  minimumSize:
                                                      const MaterialStatePropertyAll(Size.infinite),
                                                  padding: const MaterialStatePropertyAll(
                                                      EdgeInsets.zero),
                                                  shape: MaterialStatePropertyAll(
                                                    RoundedRectangleBorder(
                                                        borderRadius: BorderRadius.circular(5.r)),
                                                  ),
                                                  backgroundColor: MaterialStatePropertyAll(
                                                      ColorsUtils.parseColorFromHexString(
                                                          ColorsUtils.colorF048)),
                                                  alignment: Alignment.center),
                                              child: Text(
                                                '去拼单',
                                                style: StylesUtils.customTextStyle(),
                                              )),
                                        ),
                                      )
                                    ],
                                  ),
                                ));
                          })
                          .values
                          .toList(),
                    );
                  },
                ),
              ),
            ),
            Container(
              height: 35.h,
              padding: EdgeInsets.symmetric(horizontal: 15.w),
              alignment: Alignment.centerLeft,
              decoration: const BoxDecoration(color: Colors.white),
              child: Wrap(
                spacing: 30,
                children: [
                  Text(
                    '商品介绍',
                    style: StylesUtils.customTextStyle(color: ColorsUtils.color3333),
                  ),
                  Text(
                    '产品参数',
                    style: StylesUtils.customTextStyle(color: ColorsUtils.color9999),
                  )
                ],
              ),
            ),
            CachedNetworkImage(
              imageUrl:
                  'https://img.axureshop.com/d6/00/9e/d6009ed3a335415196f21a199d9bad93/images/商品详情/u8043.jpg',
              height: 400,
              fit: BoxFit.cover,
            ),
            Container(
              decoration: const BoxDecoration(color: Colors.white),
              padding: EdgeInsets.only(left: 15.w, right: 15.w, top: 10.h, bottom: 20.h),
              child: Column(
                children: [
                  Container(
                    alignment: Alignment.centerLeft,
                    child: Text(
                      '1. 团购商品，每次下单只能购买1件；',
                      style: StylesUtils.textStyle(
                          color: ColorsUtils.rgba(0, 0, 0, 0.647058823529412), lineHeight: 1.2.h),
                    ),
                  ),
                  Container(
                    margin: EdgeInsets.symmetric(vertical: 8.h),
                    alignment: Alignment.centerLeft,
                    child: Text(
                      '2. 不限制用户参与团购次数；',
                      style: StylesUtils.textStyle(
                          color: ColorsUtils.rgba(0, 0, 0, 0.647058823529412), lineHeight: 1.2.h),
                    ),
                  ),
                  Container(
                    alignment: Alignment.centerLeft,
                    child: Text(
                      '3. 点击分享按钮，即可邀请好友参与拼单；',
                      style: StylesUtils.textStyle(
                          color: ColorsUtils.rgba(0, 0, 0, 0.647058823529412), lineHeight: 1.2.h),
                    ),
                  ),
                  Container(
                    margin: EdgeInsets.symmetric(vertical: 8.h),
                    alignment: Alignment.centerLeft,
                    child: Text(
                      '4. 拼团时间为24小时，24小时不成团则自动退款；',
                      style: StylesUtils.textStyle(
                          color: ColorsUtils.rgba(0, 0, 0, 0.647058823529412), lineHeight: 1.2.h),
                    ),
                  ),
                  Container(
                    alignment: Alignment.centerLeft,
                    margin: EdgeInsets.only(bottom: 8.h),
                    child: Text(
                      '5. 在拼团有效期内，不允许取消拼团订单；',
                      style: StylesUtils.textStyle(
                          color: ColorsUtils.rgba(0, 0, 0, 0.647058823529412), lineHeight: 1.2.h),
                    ),
                  ),
                  Container(
                    alignment: Alignment.centerLeft,
                    child: Text(
                      '6. 拼团失败，1-3个工作日退还付款金额。',
                      style: StylesUtils.textStyle(
                          color: ColorsUtils.rgba(0, 0, 0, 0.647058823529412), lineHeight: 1.2.h),
                    ),
                  ),
                ],
              ),
            )
          ],
        ),
      ),
      bottomNavigationBar: SafeArea(
        bottom: true,
        child: Container(
          height: 40,
          alignment: Alignment.center,
          decoration:
              BoxDecoration(color: ColorsUtils.parseColorFromHexString(ColorsUtils.colorF048)),
          child: TextButton(
              onPressed: sendSpell,
              child: Text(
                '发起拼单',
                style: StylesUtils.customTextStyle(fontSize: StylesUtils.fontSize16),
              )),
        ),
      ),
    );
  }

  void openShare() {
    Get.bottomSheet(SizedBox(
      height: 280,
      child: Column(
        children: [
          Container(
            height: 40,
            alignment: Alignment.center,
            decoration:
                BoxDecoration(color: ColorsUtils.parseColorFromHexString(ColorsUtils.colorF048)),
            child: Text(
              '分享',
              style: StylesUtils.customTextStyle(fontSize: StylesUtils.fontSize16),
            ),
          ),
          Expanded(
              child: Container(
            decoration: const BoxDecoration(
              color: Colors.white,
            ),
            padding: const EdgeInsets.only(top: 20),
            child: StaggeredGrid.count(
              crossAxisCount: 3,
              crossAxisSpacing: 10,
              mainAxisSpacing: 30,
              children: [
                Column(
                  children: [
                    Center(
                      child: SvgUtils.assetName('u3728', width: 37.w, height: 30.h),
                    ),
                    Container(
                      margin: const EdgeInsets.only(top: 10),
                      alignment: Alignment.center,
                      child: Text(
                        '微信好友',
                        style: StylesUtils.customTextStyle(color: ColorsUtils.color6666),
                      ),
                    )
                  ],
                ),
                Column(
                  children: [
                    Center(
                      child: SvgUtils.assetName('u3729', width: 37.w, height: 30.h),
                    ),
                    Container(
                      margin: const EdgeInsets.only(top: 10),
                      alignment: Alignment.center,
                      child: Text(
                        '微信朋友圈',
                        style: StylesUtils.customTextStyle(color: ColorsUtils.color6666),
                      ),
                    )
                  ],
                ),
                Column(
                  children: [
                    Center(
                      child: SvgUtils.assetName('u3730', width: 37.w, height: 30.h),
                    ),
                    Container(
                      margin: const EdgeInsets.only(top: 10),
                      alignment: Alignment.center,
                      child: Text(
                        'QQ好友',
                        style: StylesUtils.customTextStyle(color: ColorsUtils.color6666),
                      ),
                    )
                  ],
                ),
                Column(
                  children: [
                    Center(
                      child: SvgUtils.assetName('u3740', width: 37.w, height: 30.h),
                    ),
                    Container(
                      margin: const EdgeInsets.only(top: 10),
                      alignment: Alignment.center,
                      child: Text(
                        'QQ空间',
                        style: StylesUtils.customTextStyle(color: ColorsUtils.color6666),
                      ),
                    )
                  ],
                ),
                Column(
                  children: [
                    Center(
                      child: SvgUtils.assetName('u3741', width: 37.w, height: 30.h),
                    ),
                    Container(
                      margin: const EdgeInsets.only(top: 10),
                      alignment: Alignment.center,
                      child: Text(
                        '新浪微博',
                        style: StylesUtils.customTextStyle(color: ColorsUtils.color6666),
                      ),
                    )
                  ],
                ),
                InkWell(
                  onTap: () {
                    ClipboardUtils.copy('text');
                  },
                  child: Column(
                    children: [
                      Center(
                        child: SvgUtils.assetName('u3737', width: 37.w, height: 30.h),
                      ),
                      Container(
                        margin: const EdgeInsets.only(top: 10),
                        alignment: Alignment.center,
                        child: Text(
                          '复制链接',
                          style: StylesUtils.customTextStyle(color: ColorsUtils.color6666),
                        ),
                      )
                    ],
                  ),
                )
              ],
            ),
          )),
          InkWell(
            onTap: closed.useThrottle2(10),
            child: Container(
              height: 40,
              alignment: Alignment.center,
              color: ColorsUtils.parseColorFromHexString(ColorsUtils.colorF2f2),
              child: Text('取消',
                  style: StylesUtils.customTextStyle(
                      fontSize: StylesUtils.fontSize16, color: ColorsUtils.color9999)),
            ),
          )
        ],
      ),
    ));
  }

  void closed() {
    Get.back();
  }

  void sendSpell() {
    Get.bottomSheet(Container(
      height: 280,
      decoration: const BoxDecoration(
        color: Colors.white,
      ),
      child: Column(
        children: [
          Container(
            height: 50,
            padding: EdgeInsets.symmetric(horizontal: 20.w),
            alignment: Alignment.centerLeft,
            child: Text(
              '选择拼团档位',
              style: StylesUtils.textStyle(
                color: ColorsUtils.rgba(0, 0, 0, 0.847058823529412),
                fontWeight: FontWeight.w700,
                fontSize: StylesUtils.fontSize18,
              ),
            ),
          ),
          Expanded(
              child: Container(
            padding: EdgeInsets.symmetric(horizontal: 15.w),
            child: Obx(() => Column(
                children: controller.teamList
                    .asMap()
                    .map((i, row) => MapEntry(
                        i,
                        InkWell(
                          onTap: () {
                            for (var e in controller.teamList) {
                              if (e == row) {
                                e.checked = !e.checked;
                              } else {
                                e.checked = false;
                              }
                            }
                            controller.teamList.refresh();
                          },
                          child: Container(
                            padding: EdgeInsets.only(bottom: 20.h),
                            child: Row(
                              mainAxisAlignment: MainAxisAlignment.spaceBetween,
                              children: [
                                Text(
                                  '${row.number}人，￥${row.price}',
                                  style: StylesUtils.textStyle(
                                      color: ColorsUtils.rgba(0, 0, 0, 0.647058823529412)),
                                ),
                                SizedBox(
                                  width: 20,
                                  height: 20,
                                  child: CustomPaint(
                                    painter: _MyCustomPainter(checked: row.checked),
                                  ),
                                )
                              ],
                            ),
                          ),
                        )))
                    .values
                    .toList())),
          )),
          Container(
            height: 40,
            alignment: Alignment.center,
            decoration:
                BoxDecoration(color: ColorsUtils.parseColorFromHexString(ColorsUtils.colorF048)),
            child: TextButton(
                onPressed: () {
                  closed();
                  Future.delayed(const Duration(milliseconds: 20), () {
                    Get.toNamed(RoutePath.groupConfirm);
                  });
                },
                child: Text(
                  '确定',
                  style: StylesUtils.customTextStyle(fontSize: StylesUtils.fontSize15),
                )),
          )
        ],
      ),
    ));
  }
}

class _MyCustomPainter extends CustomPainter {
  final bool checked;

  _MyCustomPainter({this.checked = false});

  @override
  void paint(Canvas canvas, Size size) {
    Paint paint = Paint();
    paint.isAntiAlias = true;
    paint.style = PaintingStyle.stroke;
    paint.strokeWidth = 1;
    paint.color = ColorsUtils.parseColorFromHexString(ColorsUtils.color9999);
    if (checked) {
      paint.color = ColorsUtils.parseColorFromHexString(ColorsUtils.colorF048);
      paint.style = PaintingStyle.fill;
    }
    canvas.drawCircle(Offset(size.width / 2, size.height / 2), size.width / 2, paint);
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    return this != oldDelegate;
  }
}

class _TeamworkModel {
  /// 人数
  int number;

  /// 价格
  double price;

  bool checked;

  _TeamworkModel({required this.number, required this.price, this.checked = false});
}
